﻿using Sasa.QualityTools.CodeAnalysis.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Sasa.QualityTools.CodeAnalysis.Core.Models
{
    public class RuleSet
    {
        public string Name { get; set; }

        public string Path { get; set; }


        public RuleSet()
        {
        }

        public RuleSet(string path)
        {
            Name = GetRuleSetName(path);
            Path = path;
        }


        public static IEnumerable<RuleSet> Load(string directory)
        {
            Logger.Info("Loading ruleset files from '{0}'.", directory);

            if (Directory.Exists(directory))
            {
                foreach (string path in Directory.GetFiles(directory, "*.ruleset"))
                {
                    yield return new RuleSet(path);
                }
            }
        }

        internal static string GetRuleSetName(string path)
        {
            try
            {
                var document = new XmlDocument();
                document.Load(path);
                var element = document.SelectSingleNode("/RuleSet/@Name");
                return (element != null) ? element.Value : System.IO.Path.GetFileNameWithoutExtension(path);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, Text.Format("Failed to get RuleSet name of '{0}'.", path));
                throw;
            }
        }
    }
}
